package com.clkj.mobileinspector.ui.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.OperationBean;
import com.clkj.mobileinspector.model.bean.OperationSuccessBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;
import com.lws.basic.utils.encryption.Base64Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//民警维权
public class SafeguardRightsActivity extends BaseActivity {


    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_idcard)
    EditText mEtIdcard;
    @BindView(R.id.rb_sex_1)
    RadioButton mRbSex1;
    @BindView(R.id.rb_sex_2)
    RadioButton mRbSex2;
    @BindView(R.id.rb_1)
    RadioButton mRb1;
    @BindView(R.id.rb_2)
    RadioButton mRb2;
    @BindView(R.id.et_unit)
    EditText mEtUnit;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_time)
    EditText mEtTime;
    @BindView(R.id.et_site)
    EditText mEtSite;
    @BindView(R.id.et_victimization)
    EditText mEtVictimization;
    @BindView(R.id.et_result)
    EditText mEtResult;
    @BindView(R.id.iv_evidence1)
    ImageView mIvEvidence1;
    @BindView(R.id.iv_evidence2)
    ImageView mIvEvidence2;
    @BindView(R.id.et_perpetrator)
    EditText mEtPerpetrator;
    @BindView(R.id.rb_sex_perpetrator_1)
    RadioButton mRbSexPerpetrator1;
    @BindView(R.id.rb_sex_perpetrator_2)
    RadioButton mRbSexPerpetrator2;
    @BindView(R.id.et_perpetrator_age)
    EditText mEtPerpetratorAge;
    @BindView(R.id.et_perpetrator_idcard)
    EditText mEtPerpetratorIdcard;
    @BindView(R.id.et_perpetrator_phone)
    EditText mEtPerpetratorPhone;
    @BindView(R.id.btn)
    Button mBtn;
    private String mPic1;
    private String mPic2;

    @Override
    public int setLayoutId() {
        return R.layout.activity_safeguard_rights;
    }


    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);

        if (!TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            mBtn.setVisibility(View.INVISIBLE);
            List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean1 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean1.setKey("id");
            bean1.setRelationOperator("=");
            bean1.setValue(getIntent().getStringExtra("id"));
            list.add(bean1);
            getData(list);

        }
    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi rightsRecordDetails = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.rightsRecordDetails);

        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();


        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(20);

        String json = JsonUtils.query(keyValueListBeanList, "id,policename,policeidcard,policesex,policetype,policeunit,policephone,crimetime,crimeplace,infringement,processingresults,evidencepic1,evidencepic2,evidencepic3,evidencepic4,offendername,offendersex,offenderage,offenderidcard,offenderphone,createuser,createidcard,createdate"
                , rightsRecordDetails.getResourceId(), orderByList, page, rightsRecordDetails.getResourceRegionalismCode());
        OkHttpUtils.post(rightsRecordDetails.getResourceAddress(), json, QuerySuccessBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();
                if (querySuccessBean.getCode().equals("200")) {
                    QuerySuccessBean.DataBean.DataListBean bean = querySuccessBean.getData().getDataList().get(0);
                    mEtName.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "policename"));
                    mEtIdcard.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "policeidcard"));
                    if (JsonUtils.queryGetFiled(bean.getFieldValues(), "policesex").equals("1")) {
                        mRbSex1.setChecked(true);
                    } else {
                        mRbSex2.setChecked(true);
                    }
                    //民警 辅警
                    if (JsonUtils.queryGetFiled(bean.getFieldValues(), "policetype").equals("1")) {
                        mRb1.setChecked(true);
                    } else {
                        mRb2.setChecked(true);
                    }
                    //工作单位
                    mEtUnit.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "policeunit"));
                    //电话
                    mEtPhone.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "policephone"));
                    //案发地点
                    mEtSite.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "crimeplace"));
                    if (!TextUtils.isEmpty((JsonUtils.queryGetFiled(bean.getFieldValues(), "crimetime"))) ){
                        mEtTime.setText(TimeUtils.yyyyMMdd(JsonUtils.queryGetFiled(bean.getFieldValues(), "crimetime")));
                    }
                    mEtVictimization.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "infringement"));
                    mEtResult.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "processingresults"));
                    String path1 = getFilesDir().getPath() + "/" + TimeUtils.getTodayDateTime() + "pic1.jpg";
                    String path2 = getFilesDir().getPath() + "/" + TimeUtils.getTodayDateTime() + "pic2.jpg";
//                    String path3 = getFilesDir().getPath() + "/" + TimeUtils.getTodayDateTime() + "pic3.jpg";
//                    String path4 = getFilesDir().getPath() + "/" + TimeUtils.getTodayDateTime() + "pic4.jpg";

                    if (!TextUtils.isEmpty(JsonUtils.queryGetFiled(bean.getFieldValues(), "evidencepic1"))) {
                        Base64Utils.base64ToFile(JsonUtils.queryGetFiled(bean.getFieldValues(), "evidencepic1"), path1);
                        Glide.with(SafeguardRightsActivity.this).load(path1).into(mIvEvidence1);

                    }
                    if (!TextUtils.isEmpty(JsonUtils.queryGetFiled(bean.getFieldValues(), "evidencepic2"))) {
                        Base64Utils.base64ToFile(JsonUtils.queryGetFiled(bean.getFieldValues(), "evidencepic2"), path2);
                        Glide.with(SafeguardRightsActivity.this).load(path2).into(mIvEvidence2);
                    }
                    mEtPerpetrator.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "offendername"));
                    mEtPerpetratorAge.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "offenderage"));
                    if (JsonUtils.queryGetFiled(bean.getFieldValues(), "offendersex").equals("1")) {
                        mRbSexPerpetrator1.setChecked(true);
                    } else {
                        mRbSexPerpetrator2.setChecked(true);
                    }
                    mEtPerpetratorIdcard.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "offenderidcard"));
                    mEtPerpetratorPhone.setText(JsonUtils.queryGetFiled(bean.getFieldValues(), "offenderphone"));
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    @OnClick({R.id.iv_evidence1, R.id.iv_evidence2, R.id.btn, R.id.et_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_time:
                showTime();
                break;
            case R.id.iv_evidence1:
                openPhoto(1);
                break;
            case R.id.iv_evidence2:
                openPhoto(2);
                break;
            case R.id.btn:
                String name = mEtName.getText().toString();
                String idcard = mEtIdcard.getText().toString();
                String sex;
                if (mRbSex1.isChecked()) {
                    sex = "1";
                } else {
                    sex = "2";
                }
                String type;//1民警2辅警
                if (mRb1.isChecked()) {
                    type = "1";
                } else {
                    type = "2";
                }
                String unit = mEtUnit.getText().toString();
                String phone = mEtPhone.getText().toString();
                String time = mEtTime.getText().toString();
                String site = mEtSite.getText().toString();
                String victimization = mEtVictimization.getText().toString();
                String result = mEtResult.getText().toString();
                String perpetrator = mEtPerpetrator.getText().toString();
                String perpetratorSex;
                if (mRbSexPerpetrator1.isChecked()) {
                    perpetratorSex = "1";
                } else {
                    perpetratorSex = "2";
                }
                String perpetratorAge = mEtPerpetratorAge.getText().toString();
                String perpetratorIdcard = mEtPerpetratorIdcard.getText().toString();
                String perpetratorPhone = mEtPerpetratorPhone.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    MyToast.show("姓名不能为空");
                } else if (TextUtils.isEmpty(idcard)) {
                    MyToast.show("身份证号不能为空");
                } else if (TextUtils.isEmpty(phone)) {
                    MyToast.show("手机号码不能为空");
                } else if (TextUtils.isEmpty(site)) {
                    MyToast.show("案发地点不能为空");
                } else if (TextUtils.isEmpty(victimization)) {
                    MyToast.show("受侵害情况不能为空");
                } else if (TextUtils.isEmpty(result)) {
                    MyToast.show("处理结果不能为空");
                } else if (TextUtils.isEmpty(perpetrator)) {
                    MyToast.show("违法人姓名不能为空");
                } else if (TextUtils.isEmpty(perpetratorIdcard)) {
                    MyToast.show("违法人身份证号不能为空");
                } else if (TextUtils.isEmpty(perpetratorPhone)) {
                    MyToast.show("违法人电话不能为空");
                } else if (TextUtils.isEmpty(time)) {
                    MyToast.show("请选择案发时间");
                } else {
                    showLoading();

                    //接口
                    ResourceApi rightsRecordAdd = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.rightsRecordAdd);

                    List<OperationBean.ParameterBean.OperationsBean.DataBean> dataList = new ArrayList<>();
                    OperationBean.ParameterBean.OperationsBean.DataBean data1 = new OperationBean.ParameterBean.OperationsBean.DataBean();
                    List<OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean> fieldValuesBeanList = new ArrayList<>();
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues1 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues1.setField("policename");
                    fieldValues1.setValue(name);
                    fieldValuesBeanList.add(fieldValues1);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues2 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues2.setField("policeidcard");
                    fieldValues2.setValue(idcard);
                    fieldValuesBeanList.add(fieldValues2);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues3 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues3.setField("policesex");
                    fieldValues3.setValue(sex);
                    fieldValuesBeanList.add(fieldValues3);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues4 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues4.setField("policetype");
                    fieldValues4.setValue(type);
                    fieldValuesBeanList.add(fieldValues4);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues5 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues5.setField("policeunit");
                    fieldValues5.setValue(unit);
                    fieldValuesBeanList.add(fieldValues5);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues6 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues6.setField("policephone");
                    fieldValues6.setValue(phone);
                    fieldValuesBeanList.add(fieldValues6);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues7 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues7.setField("crimetime");
                    fieldValues7.setValue(time);
                    fieldValuesBeanList.add(fieldValues7);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues8 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues8.setField("crimeplace");
                    fieldValues8.setValue(site);
                    fieldValuesBeanList.add(fieldValues8);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues9 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues9.setField("infringement");
                    fieldValues9.setValue(victimization);
                    fieldValuesBeanList.add(fieldValues9);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues10 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues10.setField("processingresults");
                    fieldValues10.setValue(result);
                    fieldValuesBeanList.add(fieldValues10);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues11 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues11.setField("evidencepic1");
                    fieldValues11.setValue(mPic1);
                    fieldValuesBeanList.add(fieldValues11);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues12 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues12.setField("evidencepic2");
                    fieldValues12.setValue(mPic2);
                    fieldValuesBeanList.add(fieldValues12);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues13 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues13.setField("offendername");
                    fieldValues13.setValue(perpetrator);
                    fieldValuesBeanList.add(fieldValues13);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues14 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues14.setField("offendersex");
                    fieldValues14.setValue(perpetratorSex);
                    fieldValuesBeanList.add(fieldValues14);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues15 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues15.setField("offenderage");
                    fieldValues15.setValue(perpetratorAge);
                    fieldValuesBeanList.add(fieldValues15);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues16 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues16.setField("offenderidcard");
                    fieldValues16.setValue(perpetratorIdcard);
                    fieldValuesBeanList.add(fieldValues16);
                    OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean fieldValues17 = new OperationBean.ParameterBean.OperationsBean.DataBean.FieldValuesBean();
                    fieldValues17.setField("offenderphone");
                    fieldValues17.setValue(perpetratorPhone);
                    fieldValuesBeanList.add(fieldValues17);


                    data1.setFieldValues(fieldValuesBeanList);
                    dataList.add(data1);
                    String json = JsonUtils.operation(null, 1, rightsRecordAdd.getResourceId(), dataList, rightsRecordAdd.getResourceRegionalismCode());
                    LogUtils.logUpload("民警维权添加", "2", rightsRecordAdd.getResourceId(), rightsRecordAdd.getResourceAddress(), json, "", "成功", "", "");

                    OkHttpUtils.post(rightsRecordAdd.getResourceAddress(), json, OperationSuccessBean.class).compose(this.bindToLifecycle()).subscribe(new ObserverOnNext<OperationSuccessBean>() {
                        @Override
                        public void onNext(OperationSuccessBean operationSuccessBean) {
                            dismissLoading();
                            if (operationSuccessBean.getCode().equals("200")) {
                                MyToast.show("操作成功");
                                finish();

                            } else {
                                MyToast.show(operationSuccessBean.getMessage());
                            }

                        }


                    });

                }


                break;
        }
    }

    /**
     * 打开相册
     */
    public void openPhoto(int request) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .compress(true)
                .forResult(request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            final List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
            switch (requestCode) {
                case 1:
                    Glide.with(SafeguardRightsActivity.this).load(list.get(0).getCompressPath()).into(mIvEvidence1);                    //图片转成base64字符串
                    mPic1 = Base64Utils.imageToBase64(list.get(0).getCompressPath());
                    break;
                case 2:
                    Glide.with(SafeguardRightsActivity.this).load(list.get(0).getCompressPath()).into(mIvEvidence2);                    //图片转成base64字符串
                    mPic2 = Base64Utils.imageToBase64(list.get(0).getCompressPath());
                    break;


            }
        }


    }

    /**
     * 显示时间
     */
    private void showTime() {
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                mEtTime.setText(time);

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
